package org.example.myl.utils;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.util.UUID;
@Slf4j
@Component
public class MinioUtils {
    @Autowired
    private  MinioClient minioClient;
    @Value("${minio.endpoint}")
    private  String endpoint;
    @Value("${minio.bucketName}")
    private  String bucketName;

    public String upload(MultipartFile file) {
        //获取原文件名
        String fileName = file.getOriginalFilename();
        //定义新文件名
        String NewFileName = "";
        if (fileName != null) {
            //新文件名
            NewFileName = UUID.randomUUID()
                    + fileName.substring(fileName.lastIndexOf("."));
        }

        try (InputStream in = file.getInputStream()) { // 使用try-with-resources自动关闭InputStream
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(NewFileName) // 用新文件名存入
                    .stream(in, in.available(), -1)
                    .contentType(file.getContentType())
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
        }
//        try {
//            InputStream in = file.getInputStream();
//            minioClient.putObject(PutObjectArgs.builder()
//                    .bucket(bucketName)
//                    .object(NewFileName)//用新文件名存入
//                    .stream(in, in.available(), -1)
//                    .contentType(file.getContentType())
//                    .build());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        log.info(endpoint + "/" + bucketName + "/" + NewFileName);
        return endpoint + "/" + bucketName + "/" + NewFileName;//返回访问的路径
    }
}
